#include "stdafx.h"
#include "Heightmap.h"
#include "../../EdgeGraphics/GraphicsManager.h"
#include <memory>
#include <fstream>
#include <assert.h>
using namespace std;


Heightmap::Heightmap(const char* filename, unsigned int MapWidth, unsigned int MapHeight, float lowest, float highest)
{
	this->width = MapWidth;
	this->height = MapHeight;
	this->lowest = lowest;
	this->heighest = highest;

	fstream file(filename, ios::in | ios::binary);
	assert(file.is_open() && "Could not find file!");

	unsigned int height_dataLength = width * height;
	rawHeightData = new float[height_dataLength];
	file.read(reinterpret_cast<char*>(rawHeightData), height_dataLength * sizeof(float));
	unsigned int normal_dataLength = width * height * sizeof(Vector3);
	rawNormalData = new Vector3[normal_dataLength];
	file.read(reinterpret_cast<char*>(rawNormalData), normal_dataLength);
	file.close();
	
	// Make height texture
	heightData = new Texture2D(width, height, DXGI_FORMAT_R32_FLOAT, nullptr, D3D11_BIND_SHADER_RESOURCE, D3D11_CPU_ACCESS_WRITE, D3D11_USAGE_DYNAMIC);
	heightData->setData(rawHeightData, sizeof(float));

	// Make normal texture
	normalData = new Texture2D(width, height, DXGI_FORMAT_R32G32B32_FLOAT, nullptr, D3D11_BIND_SHADER_RESOURCE, D3D11_CPU_ACCESS_WRITE, D3D11_USAGE_DYNAMIC);
	normalData->setData(rawNormalData, sizeof(Vector3));
}

/*virtual*/ Heightmap::~Heightmap(void)
{
	delete rawNormalData;
	delete rawHeightData;

	delete normalData;
	delete heightData;
}

// retrieve the height at a spesific point in the map
float Heightmap::GetHeightAt(int x,  int y)
{
	x *= 20;
	y *= 20;

	if (x < 0 || (unsigned int)x >= width ||
		y < 0 || (unsigned int)y >= height)
		return 0.f;
	
	return lowest + rawHeightData[x + y * width] * (heighest - lowest);
}